package com.yuyou.tas.feedback.service.impl;

import com.yuyou.tas.feedback.mapper.FeedbackClassMapper;
import com.yuyou.tas.feedback.service.*;
import com.yuyou.tas.service.api.feedback.dto.FeedbackClassDTO;
import com.yuyou.tas.service.api.feedback.dto.FeedbackClassPage;
import com.yuyou.tas.service.api.feedback.dto.FeedbackSituationMoreVo;
import com.yuyou.tas.service.api.feedback.entity.*;
import com.yuyou.tas.service.api.feedback.vo.resp.*;
import com.yuyou.tas.service.api.lesson.dto.LessonClassDTO;
import com.yuyou.tas.service.api.lesson.service.LessonClassAPI;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.feedback.FeedbackSituationEnums;
import com.yuyou.tas.util.enums.feedback.MediaOperateEnums;
import com.yuyou.tas.util.tool.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class FeedbackClassServiceImpl implements IFeedbackClassService {

    @Autowired
    private FeedbackClassMapper mapper;

    @Autowired
    private LessonClassAPI lessonClassAPI;

    @Autowired
    private IFeedbackService feedbackService;

    @Autowired
    private IFeedbackSituationService feedbackSituationService;

    @Autowired
    private IFeedbackSituationConfigService feedbackSituationConfigService;

    @Autowired
    private IFeedbackStudentExceService feedbackStudentExceService;

    @Autowired
    private IFeedbackCommentService feedbackCommentService;

    @Autowired
    private IFeedbackTeacherPraiseService feedbackTeacherPraiseService;

    @Autowired
    private IFeedbackNoteService feedbackNoteService;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(FeedbackClass record) {
        return mapper.insert(record);
    }

    @Override
    public FeedbackClass selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(FeedbackClass record) {
        return mapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public ResBoolSimpleInfo<FeedbackClass> addFeedbackClass(Long classId, Long userId, Long organId) {
        FeedbackClass feedbackClass = new FeedbackClass();
        feedbackClass.setAuthOrganizationId(organId);
        feedbackClass.setCreateTime(new Date());
        feedbackClass.setId(Sequence.getSequence().nextId());
        feedbackClass.setLessonClassId(classId);
        feedbackClass.setTeacherId(userId);

        Integer sort = mapper.getMaxSortByClassId(classId);
        feedbackClass.setSort(sort == null ? 0 : sort+1);

        mapper.insert(feedbackClass);

        //添加笔记图片
        /*if(!StringUtils.isEmpty(urls)){
            feedbackNoteService.addFeedbackNote(feedbackClass.getId() , urls , organId , userId);
        }*/

        return new ResBoolSimpleInfo(true , null ,feedbackClass);
    }

    @Override
    public ResBoolSimpleInfo<FeedbackEditDetail> getFeedbackEditDetail(Long feedbackClassId, Long userId, Long organId) {
        FeedbackClass feedbackClass = mapper.selectByPrimaryKey(feedbackClassId);
        if(feedbackClass != null){
            LessonClassDTO classDTO = lessonClassAPI.findLessonClassDTOByClassId(feedbackClass.getLessonClassId());
            if(classDTO != null){
                FeedbackEditDetail feedbackEditDetail = new FeedbackEditDetail();
                DefindBeanUtils.copyProperties(classDTO , feedbackEditDetail);

                //优秀学生笔记
                List<FeedbackNoteMoreVo> noteList = feedbackNoteService.findByFeedClassId(feedbackClassId);
                noteList.forEach(feedbackNoteMoreVo -> {
                    if(MediaOperateEnums.status.init.getValue() == feedbackNoteMoreVo.getStatus()
                            ||MediaOperateEnums.status.fail.getValue() == feedbackNoteMoreVo.getStatus()
                            ||MediaOperateEnums.status.operating.getValue() == feedbackNoteMoreVo.getStatus()){//微信
                        feedbackNoteMoreVo.setType(MediaOperateEnums.type.wechat.getValue());
                    }else {//七牛
                        feedbackNoteMoreVo.setType(MediaOperateEnums.type.qiniu.getValue());
                    }
                });
                feedbackEditDetail.setNotes(noteList);

                //班级学生列表
                List<StudentFeedBackEdit> stus = feedbackService.findStuDetailByFeedClassId(feedbackClassId , feedbackClass.getLessonClassId());
                //学生人数
                feedbackEditDetail.setStuCount(stus.size());
                Long finish = stus.stream().filter(studentFeedBackEdit -> studentFeedBackEdit.getStatus() == 1).count();
                //已发布人数
                feedbackEditDetail.setFinishCount(Integer.valueOf(finish+""));

                //该班级反馈下所有详细内容
                List<FeedbackSituationMoreVo> situations = feedbackSituationService.findByFeedbackClassId(feedbackClassId);
                Map<Long , List<FeedbackSituationMoreVo>> situationMap = BeanUtils.toGroup(situations , "stuId");

                //该班级反馈的全部优秀学生
                List<FeedbackStudentExce> exces = feedbackStudentExceService.getByFeedbackClassId(feedbackClassId);
                Map<Long , FeedbackStudentExce> exceMap = BeanUtils.toMap(exces , "studentId");

                //该班级反馈的所有回复信息
                List<FeedbackComment> comments = feedbackCommentService.findByFeedbackClassId(feedbackClassId);
                Map<Long , List<FeedbackComment>> commentMap = BeanUtils.toGroup(comments , "feedbackId");

                //全部送花记录
                List<FeedbackTeacherPraise> praises = feedbackTeacherPraiseService.findByFeedbackClassId(feedbackClassId);
                Map<Long , FeedbackTeacherPraise> praiseMap = BeanUtils.toMap(praises , "sendUserId");

                //全部标签
                List<FeedbackSituationConfig> configs = feedbackSituationConfigService.getAll();
                //学习表现，未选状态
                List<SituationConfigVo> configVos = new ArrayList<>();
                configs.forEach(f -> {
                    SituationConfigVo situationConfigVo = new SituationConfigVo();
                    situationConfigVo.setId(f.getId());
                    situationConfigVo.setIs_check(0);
                    situationConfigVo.setName(f.getName());
                    situationConfigVo.setSort(f.getSort());
                    situationConfigVo.setCategory(f.getCategory());
                    configVos.add(situationConfigVo);
                });

                //给每个学生赋值
                stus.forEach(studentFeedBackEdit -> {

                    //设置拼音字母
                    if(!StringUtils.isEmpty(studentFeedBackEdit.getStuName())){
                        studentFeedBackEdit.setSpell(PingYinUtil.toPinyin(studentFeedBackEdit.getStuName().trim()));
                        studentFeedBackEdit.setFirstSpell(studentFeedBackEdit.getSpell().substring(0 , 1).toUpperCase());
                    }

                    FeedbackDetailEdit feedbackDetailEdit = new FeedbackDetailEdit();
                    if(studentFeedBackEdit.getStatus() != -1 && situationMap.containsKey(studentFeedBackEdit.getStuId())){//有编辑记录的学生
                            List<FeedbackSituationMoreVo> ls = situationMap.get(studentFeedBackEdit.getStuId());
                            Map<Integer , List<FeedbackSituationMoreVo>> types = BeanUtils.toGroup(ls , "type");
                            if(!CollectionUtils.isEmpty(ls)){
                                studentFeedBackEdit.setUpdateTime(ls.get(0).getCreateTime());
                            }
                            //设置学习表现为选中状态
                            List<SituationConfigVo> situationConfigVos = new ArrayList<>(configVos.size());
                            situationConfigVos = ListUtil.deepCopy(configVos);
                            situationConfigVos.forEach(situationConfigVo ->
                                ls.forEach(feedbackSituationMoreVo -> {
                                    if(feedbackSituationMoreVo.getType() == FeedbackSituationEnums.type.behaviour.getValue() && situationConfigVo.getId().equals(feedbackSituationMoreVo.getSituationId())){
                                        situationConfigVo.setIs_check(1);
                                    }
                                })
                            );
                            feedbackDetailEdit.setLabels(situationConfigVos);

                            //图片
                            if(types.containsKey(FeedbackSituationEnums.type.picture.getValue())){
                                List<FeedbackSituationMoreVo> contents = types.get(FeedbackSituationEnums.type.picture.getValue());
                                List<MediaVo> mediaVos = new ArrayList<>();
                                contents.forEach(feedbackSituationMoreVo -> {
                                    MediaVo mediaVo = new MediaVo();
                                    mediaVo.setUrl(feedbackSituationMoreVo.getMedia());
                                    if(MediaOperateEnums.status.init.getValue() == feedbackSituationMoreVo.getStatus()
                                            ||MediaOperateEnums.status.fail.getValue() == feedbackSituationMoreVo.getStatus()
                                            ||MediaOperateEnums.status.operating.getValue() == feedbackSituationMoreVo.getStatus()){
                                        mediaVo.setType(MediaOperateEnums.type.wechat.getValue());
                                        mediaVo.setWeixinMediaId(feedbackSituationMoreVo.getWeixinMediaId());
                                    }else{
                                        mediaVo.setType(MediaOperateEnums.type.qiniu.getValue());
                                    }
                                    mediaVos.add(mediaVo);
                                });
//                                List<String> medias = contents.stream().map(FeedbackSituationMoreVo :: getMedia).collect(Collectors.toList());
                                feedbackDetailEdit.setPicturesUrl(mediaVos);
                            }


                            //音频
                            if(types.containsKey(FeedbackSituationEnums.type.voice.getValue())){
                                List<FeedbackSituationMoreVo> contents = types.get(FeedbackSituationEnums.type.voice.getValue());
                                List<MediaVo> mediaVos = new ArrayList<>();
                                contents.forEach(feedbackSituationMoreVo -> {
                                    MediaVo mediaVo = new MediaVo();
                                    mediaVo.setUrl(feedbackSituationMoreVo.getMedia());
                                    if(MediaOperateEnums.status.init.getValue() == feedbackSituationMoreVo.getStatus()
                                            ||MediaOperateEnums.status.fail.getValue() == feedbackSituationMoreVo.getStatus()
                                            ||MediaOperateEnums.status.operating.getValue() == feedbackSituationMoreVo.getStatus()){
                                        mediaVo.setType(MediaOperateEnums.type.wechat.getValue());
                                        mediaVo.setWeixinMediaId(feedbackSituationMoreVo.getWeixinMediaId());
                                        mediaVo.setTime(feedbackSituationMoreVo.getTime());
                                    }else{
                                        mediaVo.setType(MediaOperateEnums.type.qiniu.getValue());
                                        mediaVo.setTime(feedbackSituationMoreVo.getTime());
                                    }
                                    mediaVos.add(mediaVo);
                                });
//                                List<String> medias = contents.stream().map(FeedbackSituationMoreVo :: getMedia).collect(Collectors.toList());
                                feedbackDetailEdit.setAudiosUrl(mediaVos);
                            }


                            //文字点评
                            if(types.containsKey(FeedbackSituationEnums.type.content.getValue())){
                                List<FeedbackSituationMoreVo> contents = types.get(FeedbackSituationEnums.type.content.getValue());
                                feedbackDetailEdit.setContent(contents.get(0).getSituation());
                            }
                    }else{//初始化学生
                        feedbackDetailEdit.setLabels(configVos);//全部标签未未选状态
                    }

                    //设置是否优秀学生
                    if(exceMap.containsKey(studentFeedBackEdit.getStuId())){
                        feedbackDetailEdit.setIs_exec(true);
                        feedbackDetailEdit.setReason(exceMap.get(studentFeedBackEdit.getStuId()).getReason());
                    }else{
                        feedbackDetailEdit.setIs_exec(false);
                    }


                    //设置反馈的回复信息
                    feedbackDetailEdit.setComments(commentMap.get(studentFeedBackEdit.getFeedbackId()));
                    if(!CollectionUtils.isEmpty(feedbackDetailEdit.getComments())){
                        feedbackDetailEdit.getComments().forEach(feedbackComment -> {
                            if(feedbackComment.getType() == 0 && feedbackComment.getIsRead() == 0 && userId.equals(studentFeedBackEdit.getCreateUserId())){//feedback创建人才提醒
                                feedbackDetailEdit.setUnreadCount(feedbackDetailEdit.getUnreadCount() == null ? 1 : feedbackDetailEdit.getUnreadCount()+1);
                            }
                        });
                    }

                    //送花信息
                    feedbackDetailEdit.setFlowerCount(praises.size());
                    if(praiseMap.containsKey(studentFeedBackEdit.getStuId())){//已送花
                        feedbackDetailEdit.setFlowerStatus(1);
                    }


                    studentFeedBackEdit.setFeedbackDetailEdit(feedbackDetailEdit);
                });

                //根据拼音排序
                Collections.sort(stus , (o1, o2) -> {
                    int result = 0;
                    if(!o1.getSpell().equals(o2.getSpell())){//拼音不同
                        String[] arr = {o1.getSpell() , o2.getSpell()};
                        Arrays.sort(arr);
                        if(o1.getSpell().equals(arr[0])){//数组排序完，第一个还是原来的第一个，代表o1的比较小
                            result = -1;
                        }else {//两个字符发生位置调换
                            result = 1;
                        }
                    }
                    return result;
                });

                feedbackEditDetail.setList(stus);
                return new ResBoolSimpleInfo(true,null,feedbackEditDetail);
            }
        }

        return null;
    }

    @Override
    public ResBoolSimpleInfo<FeedbackClassPage> findFeedbackClass(Long classId, Long userId, Long organId, Integer pageIndex, Integer pageSize) {
        Integer count = mapper.findFeedbackClassCount(classId);
        FeedbackClassPage feedbackClassPage = new FeedbackClassPage();
        List<FeedbackClassDTO> list = new ArrayList<>();
        if(count != null && count > 0){
            //获取班级学生人数
            Integer stuCount = lessonClassAPI.getStudentCountByClassId(classId);

            Integer totalPage = (count / pageSize) + (count % pageSize > 0 ? 1 : 0);
            Integer fromRecord = pageSize * pageIndex - pageSize;
            Integer toRecord = pageSize;

            feedbackClassPage.setPageIndex(pageIndex);
            feedbackClassPage.setPageSize(pageSize);
            feedbackClassPage.setTotal(count);
            feedbackClassPage.setTotalPage(totalPage);

            list = mapper.findFeedbackClass(classId ,stuCount,userId, fromRecord , toRecord);
        }
        feedbackClassPage.setList(list);
        return new ResBoolSimpleInfo(true , null,feedbackClassPage);
    }

    @Override
    public ResBoolSimpleInfo<List<FeedbackClassesVo>> findAllClassFeedback(Long teacherId , Long trimesterId) {
        List<FeedbackClassesVo> list = lessonClassAPI.findFeedbackLessonClassByTeacher(teacherId , trimesterId).getData();
        list.forEach(feedbackClassesVo ->
            feedbackClassesVo.getClasses().forEach(feedbackLessonClassDTO -> {
                feedbackLessonClassDTO.setFeedbackClassDTOS(mapper.findFeedbackClass(feedbackLessonClassDTO.getId() , feedbackLessonClassDTO.getStuCount() ,teacherId, null , null));
                if(!CollectionUtils.isEmpty(feedbackLessonClassDTO.getFeedbackClassDTOS())){
                    feedbackLessonClassDTO.getFeedbackClassDTOS().forEach(feedbackClassDTO -> {
                        if(feedbackClassDTO.getUnreadCount() != null && feedbackClassDTO.getUnreadCount() != 0){
                            feedbackLessonClassDTO.setUnreadCount(feedbackLessonClassDTO.getUnreadCount() == null ? feedbackClassDTO.getUnreadCount() : feedbackClassDTO.getUnreadCount() + feedbackLessonClassDTO.getUnreadCount());
                        }
                    });
                }
            })
        );
        return new ResBoolSimpleInfo(true , null,list);
    }
}